package com.gzcc.controller;

import com.gzcc.model.Role;
import com.gzcc.model.User;
import com.gzcc.repository.RoleRepository;
import com.gzcc.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Optional;


/**
* 描述: 用户
* @Author: Mr.Zhong
* @Date: 2018/6/14
*/
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;

    /**
    * 描述: 跳转用户列表
    * @Author: Mr.Zhong
    * @Date: 2018/6/14
    */
    @GetMapping()
    public ModelAndView userList() {
        ModelAndView mv = new ModelAndView();
        List<User> users = userRepository.findAll();
        mv.addObject("users", users);
        mv.setViewName("backend/user/user_list.btl");
        return mv;
    }



    /**
    * 描述: 用户列表api
    * @Author: Mr.Zhong
    * @Date: 2018/6/14
    */
    @GetMapping("/api")
    @ResponseBody
    public List<User> userListApi() {
        List<User> users = userRepository.findAll();
        return users;
    }

    /**
    * 描述: 添加用户
    * @Author: Mr.Zhong
    * @Date: 2018/6/14
    */
    @RequestMapping(value = "form", method = RequestMethod.POST)
    @ResponseBody
    public User saveForm(User user) {
        Optional<Role> roleOptional = roleRepository.findById(2);
        userRepository.save(user);
        return user;
    }

    /**
    * 描述: 删除用户
    * @Author: Mr.Zhong
    * @Date: 2018/6/14
    */
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(int id) {
        userRepository.deleteById(id);
        return "redirect:/user";
    }

    /**
    * 描述: 编辑用户
    * @Author: Mr.Zhong
    * @Date: 2018/6/14
    */
    @RequestMapping(value = "edit", method = RequestMethod.GET)
    public ModelAndView edit(int id) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("backend/editUser.btl");
        User user = userRepository.getOne(id);
        mv.addObject("user", user);
        return mv;
    }

   /**
   * 描述: 查询用户
   * @Author: Mr.Zhong
   * @Date: 2018/6/14
   */
    @RequestMapping("query")
    @ResponseBody
    public List<User> query(User user) {
        List<User> users = userRepository.findByKey(user.getName());
        return users;
    }


//    @RequestMapping("/updatePassword")
//    public String updatePassword(HttpServletRequest request){
//        String oldpwd = request.getParameter("oldpwd");
//        String newpwd = request.getParameter("newpwd");
//        User user = userRepository.findByPassword(oldpwd);
//        if(user==null){
//            return "password";
//        }
//        user.setPassword(newpwd);
//        userRepository.save(user);
//        return "login";
//    }


}



